package com.macro.mall.portal.exception;

import com.macro.mall.common.api.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;


/**
 * Global Exception Handle
 *
 */
@RestControllerAdvice
class GlobalOrderExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalOrderExceptionHandler.class);

    @ExceptionHandler(BaseException.class)
    public ResponseEntity<?> handleBaseException(BaseException base) {
        log.error("BaseException:{}", base.getErrorMessage());

        return ResponseEntity.status(HttpStatus.OK).body(CommonResult.validateFailed(base.getErrorMessage()));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<?> paramException(MethodArgumentNotValidException base) {
        List<ObjectError> allErrors = base.getBindingResult().getAllErrors();
        List<String> errors = allErrors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
        return ResponseEntity.status(HttpStatus.OK).body(CommonResult.validateFailed(errors.get(0)));
    }
}